import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:intl/intl.dart';
import 'package:loadmore/loadmore.dart';
import 'package:xlsk/api/model/class.dart';
import 'package:xlsk/components/checkview.dart';
import 'package:xlsk/components/dropdown.dart';
import 'package:xlsk/components/empty.dart';
import 'package:xlsk/components/tabs.dart';
import 'package:xlsk/components/timetable.dart';
import 'package:xlsk/routes/xlsk_router.dart';
import 'package:xlsk/utils/dimension.dart';

class ClassRecord extends StatefulWidget {
  List RiKeBiao_data = [];
  int RiKeBiao_count = 0;
  int RiKeBiao_page = 1;
  List riKeBiao_tabs = [];
  int riKeBiao_tabs_current = 1;
  List RiKeBiao_data_now = [];

  @override
  State<StatefulWidget> createState() {
    return _classRecordState();
  }
}

class _classRecordState extends State<ClassRecord> {
  int current = 0;

  List riKeBiao_tabs_value = [];
  List riKeBiao_is_take_list = [
    {'id':'0','title':'否'},
    {'id':'1','title':'是'},
  ];
  List riKeBiao_daoke_status_list = [
    {'id':'1','title':'全到'},
    {'id':'2','title':'未全到'},
  ];
  String riKeBiao_is_take = '0';
  String riKeBiao_daoke_status = '1';
  double riKeBiao_contentHeight = 0;
  bool riKeBiao_keepShow = false;

  //周课表参数
  List<dynamic> leftList = [];
  List<dynamic> containerList = [];
  int zkb_picker_current = 1;


  GlobalKey _anchorKey = GlobalKey();

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance?.addPostFrameCallback((_) {
      RenderBox renderBox = _anchorKey.currentContext?.findRenderObject() as RenderBox;
      var offset = renderBox.localToGlobal(Offset.zero);
      var _dpHeight = MediaQuery.of(context).size.height;
      setState(() {
        riKeBiao_contentHeight = _dpHeight - offset.dy;
      });
      getRiKeBiaoData();
      getZhouKeBiaoData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: current!=1?Text("课程记录",style: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(17),fontWeight: FontWeight.bold)):kebiaoBar(),
        leading: GestureDetector(
          child: Icon(Icons.arrow_back_ios,color: Color.fromRGBO(31, 35, 41, 1),size: 24),
          onTap: (){
            XlskRouter.back(context);
          },
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: Container(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(bottom: Dimension(context).toPx(6)),
              child: Tabs(
                width: 375,
                current: current,
                tabList: ['日课表','周课表','请假申请'],
                callback: (idx){
                  setState(() {
                    current = idx;
                  });
                }
              ),
            ),
            Expanded(
              child: renderView(),
            )
          ],
        ),
      ),
    );
  }

  renderView(){
    switch(current){
      case 0:
        return renderRiKeBiao();
        break;
      case 1:
        return renderZhouKeBiao();
        break;
      case 2:
        return renderQingJia();
        break;
    }
  }


  renderRiKeBiao(){
    Widget view = Container(
      decoration: BoxDecoration(
          border: Border(
              top: BorderSide(
                  color: Color(0xffebedf0),
                  width: 1,
                  style: BorderStyle.solid
              )
          )
      ),
      key: _anchorKey,
      child: Stack(
        children: [
          Positioned(
            top: Dimension(context).toPx(48),
            left: 0,
            child: Container(
              width: Dimension(context).toVw(100),
              height: riKeBiao_contentHeight,
              child: widget.RiKeBiao_data.length > 0?Align(
                alignment: Alignment.topCenter,
                child: Container(
                  width: Dimension(context).toPx(343),
                  child: LoadMore(
                    isFinish: widget.RiKeBiao_data_now.length==0?true:false,
                    onLoadMore: getRiKeBiaoData,
                    child: ListView.builder(
                      itemCount: widget.RiKeBiao_count,
                      itemBuilder: (BuildContext context,int index){
                        return GestureDetector(
                          onTap: (){
                            print('all');
                          },
                          child: Container(
                            margin: EdgeInsets.only(top: Dimension(context).toPx(16)),
                            padding: EdgeInsets.only(top: Dimension(context).toPx(16),left: Dimension(context).toPx(16)),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(12)))
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(bottom: Dimension(context).toPx(8)),
                                  child: Text('${widget.RiKeBiao_data[index]['banji']}',style: TextStyle(fontSize: Dimension(context).toPx(16),color: Color(0xff646a73))),
                                ),
                                Container(
                                  margin: EdgeInsets.only(bottom: Dimension(context).toPx(8)),
                                  child: Text('${widget.RiKeBiao_data[index]['kecheng']}',style: TextStyle(fontSize: Dimension(context).toPx(16),color: Color(0xff646a73))),
                                ),
                                Container(
                                  margin: EdgeInsets.only(bottom: Dimension(context).toPx(10)),
                                  child: Row(
                                    children: [
                                      Container(
                                        margin: EdgeInsets.only(right: Dimension(context).toPx(12)),
                                        child: Text('实到/应到:',style: TextStyle(color: Color(0xff646a73),fontSize: Dimension(context).toPx(14))),
                                      ), 
                                      Text('${widget.RiKeBiao_data[index]['stu_num']}/${widget.RiKeBiao_data[index]['person_num'] != null?widget.RiKeBiao_data[index]['person_num']:0}')
                                    ],
                                  )
                                ),
                                Container(
                                    margin: EdgeInsets.only(bottom: Dimension(context).toPx(10)),
                                    child: Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(right: Dimension(context).toPx(12)),
                                          child: Text('上课时间:',style: TextStyle(color: Color(0xff646a73),fontSize: Dimension(context).toPx(14))),
                                        ),
                                        Text('${widget.RiKeBiao_data[index]['start_date']} ${widget.RiKeBiao_data[index]['timefrom']} - ${widget.RiKeBiao_data[index]['timeto']}')
                                      ],
                                    )
                                ),
                                Container(
                                  height: Dimension(context).toPx(50),
                                  padding: EdgeInsets.only(right: Dimension(context).toPx(16)),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      GestureDetector(
                                        onTap: (){
                                          print('点名');
                                        },
                                        child: Container(
                                          width: Dimension(context).toPx(50),
                                          height: Dimension(context).toPx(30),
                                          margin: EdgeInsets.only(right: Dimension(context).toPx(6)),
                                          decoration: BoxDecoration(
                                              border: Border.all(color: Color(0xff8F959E)),
                                              borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(15)))
                                          ),
                                          child: Center(
                                            child: Text('点名',style: TextStyle(color: Color(0xff1F2329),fontSize: Dimension(context).toPx(13))),
                                          ),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: (){
                                          print('点评');
                                        },
                                        child: Container(
                                          width: Dimension(context).toPx(50),
                                          height: Dimension(context).toPx(30),
                                          decoration: BoxDecoration(
                                              border: Border.all(color: Color(0xff1661FF)),
                                              borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(15)))
                                          ),
                                          child: Center(
                                            child: Text('点评',style: TextStyle(color: Color(0xff1661FF),fontSize: Dimension(context).toPx(13))),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ):Empty('暂无课程'),
            ),
          ),
          Positioned(
            left: 0,
            top: 0,
            child: Dropdown(
              keepShow: riKeBiao_keepShow,
              finish: (){
                setState(() {
                  getRiKeBiaoData();
                  riKeBiao_keepShow = false;
                });
              },
              resert: (){
                setState(() {
                  riKeBiao_is_take = '0';
                  riKeBiao_daoke_status = '1';
                  riKeBiao_keepShow = true;
                });
              },
              contentHeight: riKeBiao_contentHeight,
              children: [
                Checkview(
                  title: '已点名',
                  list: riKeBiao_is_take_list,
                  checkedId: riKeBiao_is_take,
                  onChange: (id){
                    setState(() {
                      riKeBiao_keepShow = true;
                      riKeBiao_is_take = id;
                    });
                  },
                ),
                Container(
                  margin: EdgeInsets.only(top: Dimension(context).toPx(16)),
                  child: Offstage(
                    offstage: riKeBiao_is_take=='0'?true:false,
                    child: Checkview(
                      title: '到课状态',
                      list: riKeBiao_daoke_status_list,
                      checkedId: riKeBiao_daoke_status,
                      onChange: (id){
                        setState(() {
                          riKeBiao_keepShow = true;
                          riKeBiao_daoke_status = id;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            child: Container(
              color: Colors.white,
              width: Dimension(context).toVw(80),
              height: Dimension(context).toPx(48),
              padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(16)),
              child: Container(
                width: Dimension(context).toPx(250),
                height: Dimension(context).toPx(44),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: widget.riKeBiao_tabs.length,
                  itemBuilder: (BuildContext context, int index){
                    return GestureDetector(
                      onTap: (){
                        setState(() {
                          widget.riKeBiao_tabs_current = index;
                          getRiKeBiaoData();
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(15)),
                        child: AnimatedDefaultTextStyle(
                            duration: Duration(milliseconds: 500),
                            style: TextStyle(color: widget.riKeBiao_tabs_current==index?Color(0xff2979ff):Color(0xff303133),fontSize: Dimension(context).toPx(15),fontWeight: widget.riKeBiao_tabs_current==index?FontWeight.w700:FontWeight.w400),
                            child: Center(
                              child: Text('${widget.riKeBiao_tabs[index]}'),
                            )
                        ),
                      ),
                    );
                  },
                )
              ),
            ),
          ),
        ],
      ),
    );
    return view;
  }

  Future<bool> getRiKeBiaoData() async{
    //计算时间（今天起的一周）
    var today = DateTime.now();
    int _page = widget.RiKeBiao_page;
    List riKeBiao_tabs = ['历史'];
    List riKeBiao_tabs_value = [{'start_date':'1970-01-01','jieshu_date':'${DateFormat('yyyy-MM-dd').format(today.add(Duration(days: -1)))}'}];
    riKeBiao_tabs.add('${DateFormat('EEE',"zh_CN").format(today)}(今日)');
    riKeBiao_tabs_value.add({'start_date':'${DateFormat('yyyy-MM-dd').format(today)}','jieshu_date':'${DateFormat('yyyy-MM-dd').format(today)}'});
    for(var i = 1;i<7;i++){
      var time = today.add(Duration(days: i));
      riKeBiao_tabs.add('${DateFormat('EEE',"zh_CN").format(time)}');
      riKeBiao_tabs_value.add({'start_date':'${DateFormat('yyyy-MM-dd').format(time)}','jieshu_date':'${DateFormat('yyyy-MM-dd').format(time)}'});
    }
    setState(() {
      widget.riKeBiao_tabs = riKeBiao_tabs;
      riKeBiao_tabs_value = riKeBiao_tabs_value;
    });

    // 获取日课表数据
    Map<String, dynamic> params = {
      'page':widget.RiKeBiao_page,
      'limit':10,
      'is_take':riKeBiao_is_take,
      'start_date':riKeBiao_tabs_value[widget.riKeBiao_tabs_current]['start_date'],
      'jieshu_date':riKeBiao_tabs_value[widget.riKeBiao_tabs_current]['jieshu_date']
    };
    if(riKeBiao_is_take == '1'){
      params['daoke_status'] = riKeBiao_daoke_status;
    }
    var res = await classApi().getRiKeBiao(context, params);
    if(res.length > 0){
      _page++;
    }
    List _RiKeBiao_data = widget.RiKeBiao_data;
    _RiKeBiao_data.addAll(res);
    setState(() {
      widget.RiKeBiao_data = _RiKeBiao_data;
      widget.RiKeBiao_data_now = res;
      widget.RiKeBiao_page = _page;
    });
    setState(() {
      widget.RiKeBiao_count = _RiKeBiao_data.length;
    });
    return true;
  }

  renderZhouKeBiao(){
    // Widget view = Text('周课表');
    Widget view = SyllabusPage(leftList: leftList,containerList: containerList);
    return view;
  }

  kebiaoBar(){
    List pickerdata = ['上周','本周','下周'];
    Widget view = Container(
      width: Dimension(context).toPx(176),
      child: GestureDetector(
        onTap: (){
          Pickers.showSinglePicker(context, data: pickerdata,selectData: pickerdata[zkb_picker_current],onConfirm: (p,position){
            // print('${p}-${position}');
            setState(() {
              zkb_picker_current = position;
              getZhouKeBiaoData();
            });
          });
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text('${pickerdata[zkb_picker_current]}',style: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(17),fontWeight: FontWeight.bold)),
            Icon(Icons.keyboard_arrow_down,size: Dimension(context).toPx(24),color: Color(0xFF1F2329))
          ],
        ),
      ),
    );
    return view;
  }

  getZhouKeBiaoData() async{
    //获取周开始、结束时间(默认本周)
    var moveDay = (zkb_picker_current - 1)*7;
    var today = DateTime.now();
    var today_week = today.weekday; // 获取今天的星期
    var today_week_start = today.add(Duration(days: -today_week+1+moveDay)); //本周开始
    var today_week_end = today.add(Duration(days: 7-today_week+moveDay)); //本周结束
    var start = DateFormat('yyyy-MM-dd').format(today_week_start);
    var end = DateFormat('yyyy-MM-dd').format(today_week_end);
    // print('${start}-${end}');

    var params = {
      'page': 1,
      'limit': 100,
      'start_date': start,
      'jieshu_date': end,
      'is_take': 0,
    };
    var res = await classApi().getTakeName2(context, params);
    //res数据加上week
    for(var item in res){
      List<String> ymd = item['start_date'].split('-');
      item['week'] = DateTime(int.parse(ymd[0]),int.parse(ymd[1]),int.parse(ymd[2])).weekday;
    }
    //获取左边时间列表
    List<Map<String,dynamic>> _leftList = [];
    for(var item in res){
      var find = _leftList.any((e)=>e['timefrom'] == item['timefrom']);
      if(!find){
       _leftList.add(item);
      }
    }
    //对_leftList排序
    _leftList.sort((a,b){
      int a1 = int.parse(a['timefrom'].split(':')[0]);
      int b1 = int.parse(b['timefrom'].split(':')[0]);
      if(a1 != b1){
        return a1 - b1;
      }else{
        int a2 = int.parse(a['timefrom'].split(':')[1]);
        int b2 = int.parse(b['timefrom'].split(':')[1]);
        return a2 - b2;
      }
    });
    //生成containerList数据
    List<dynamic> _containerList = [];
    for(var item in _leftList){
      List<dynamic> arr = res.where((e)=>e['timefrom'] == item['timefrom']).toList();
      for(var i = 1;i <= 7;i++){
        var obj = arr.firstWhere((e) => e['week'] == i, orElse: () => '');
        _containerList.add(obj);
      }
    }
    // print('_leftList-${_leftList}');
    // print('_containerList-${_containerList}');
    setState(() {
      leftList = _leftList;
      containerList = _containerList;
    });
  }

  renderQingJia(){
    Widget view = Text('请假');
    return view;
  }

  @override
  void dispose() {
    super.dispose();
  }
}
